package com.ruoyi.framework.web.service;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.abuwx.domain.UmsUser;
import com.ruoyi.abuwx.domain.dto.WxUserInfo;
import com.ruoyi.abuwx.domain.vo.AppLoginUser;
import com.ruoyi.abuwx.service.IUmsUserService;
import com.ruoyi.common.utils.satoken.StpClientUtil;
import com.ruoyi.common.utils.weixin.WxMaUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zouhuu
 * @description APP登录校验方法
 * @date 2022/06/23 17:11:06
 */
@Service
public class AppLoginService {

    @Autowired
    private IUmsUserService umsUserService;


    /**
     * 微信小程序登录
     */
    public AppLoginUser wxmLogin(String appId, String jscode, WxUserInfo wxUserInfo) {
        WxMaJscode2SessionResult jscode2session = null;
        System.out.println("appId: " + appId);
       System.out.println("jscode: " + jscode);
       System.out.println("wxUserInfo: " + wxUserInfo);
        try {
            jscode2session = WxMaUtils.getMaService(appId).jsCode2SessionInfo(jscode);
       } catch (WxErrorException e) {
           e.printStackTrace();
       }
        String openid = jscode2session.getOpenid();
        UmsUser umsUserParams = new UmsUser();
        umsUserParams.setWxmClientOpenid(openid);
        List<UmsUser> umsUsers = umsUserService.selectUmsUserList(umsUserParams);
        UmsUser user = null;

        if (umsUsers.size() > 0) {
            user = umsUsers.get(0);
            user.setWxmClientOpenid(openid);
            user.setAvatar(wxUserInfo.getAvatarUrl());
            user.setNickname(wxUserInfo.getNickName());
            umsUserService.updateUmsUser(user);
        } else {
            user = new UmsUser();
            user.setWxmClientOpenid(openid);
            user.setAvatar(wxUserInfo.getAvatarUrl());
            user.setNickname(wxUserInfo.getNickName());
            umsUserService.insertUmsUser(user);
        }

        AppLoginUser appLoginUser = new AppLoginUser();
        StpClientUtil.login(user.getId());
        appLoginUser.setUid(user.getId());
        appLoginUser.setUmsUser(user);
        appLoginUser.setToken(StpClientUtil.getTokenValue());
        return appLoginUser;
    }
}
